//
//  KCWorkPlanController.swift
//  MyKC
//
//  Created by yy on 2017/3/8.
//  Copyright © 2017年 com.yasuo. All rights reserved.
//

import UIKit
import SVProgressHUD
class KCWorkPlanController: UIViewController {
    
    var finishOutBack:String?
    var allOutBack: String?
    var finishNum: String?
    var allStoreNum: String?
    lazy var visitorStoreArray = [KCPlanModel]()
    //所有的拜访计划包括计划内和计划外的----来判断是否有计划没有完成
    lazy var allVisitorStoreArray = [KCPlanModel]()
    lazy var actiontitleArray = ["巡店","会议","文案","其他","出差","休假"]
    @IBOutlet weak var addBtnItem: UIBarButtonItem!
    @IBAction func addItemClick(_ sender: UIBarButtonItem) {
        var actionArray :[PopoverAction] = [PopoverAction]()
        for (index,actionTitle) in actiontitleArray.enumerated() {
            let action = PopoverAction(title: actionTitle, handler: { (action) in
                if index == 0 {
                    //跳进巡店页面
                    let xunDianController = KCXunDianViewController()
                    self.navigationController?.pushViewController(xunDianController, animated: true)
                }else {
                    //跳进其他页面,根据穿进去的值来操作
                    let meetingController = KCMeetingController()
                    meetingController.typeString = self.actiontitleArray[index]
                    self.navigationController?.pushViewController(meetingController, animated: true)
                }
            })
            actionArray.append(action!)
        }
        let popView = PopoverView()
        popView.showShade = true
        let point = CGPoint(x: ScreenWidth - 20, y: 55)
        popView.show(to: point, with: actionArray)
    }
    
    lazy var headView1: KCSystermNoticeHeadView = {
        let headView = KCSystermNoticeHeadView.systermNoticeHeadView()
        headView.lbe_head.text = "今日拜访门店"
        headView.hideView.isHidden = true
        return headView
    }()
    
    lazy var pwview: PWSCalendarView = {
        let calenderView = PWSCalendarView(frame: CGRect(x: 0, y: 100, width: ScreenWidth, height: 42 * 6 + 60), calendarType: .calendar_type_month)
        
        //默认选中的日期是当天---------
        calenderView?.selectDate = Date()
        calenderView?.delegate = self
        
        //设置手势
        let swipup = UISwipeGestureRecognizer(target: self, action: #selector(changeGesture(gesture:)))
        swipup.direction = .up
        calenderView?.addGestureRecognizer(swipup)
        
        let swipdown = UISwipeGestureRecognizer(target: self, action: #selector(changeGesture(gesture:)))
        swipdown.direction = .down
        calenderView?.addGestureRecognizer(swipdown)
        return calenderView!
    }()
    
    var tableView: UITableView?
    lazy var bgImageView: UIImageView = {
        let bgImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 100))
        let image = UIImage(named: "导航栏")
        let strImg = image?.stretchableImage(withLeftCapWidth: Int(image!.size.width * 0.5), topCapHeight: Int(image!.size.height * 0.5))
        bgImageView.image = image
        return bgImageView
    }()
    var bottonLineView = UIView()
    var putOutBtn = UIButton()
    var putInBtn = UIButton()
    var selDate = Date()
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        navigationController?.navigationBar.subviews.first?.alpha = 0
        getFinishVsAllData()
        getVisitorStoreData()
    }
    
    
    func changeGesture(gesture: UISwipeGestureRecognizer) {
        if gesture.direction == .down {
            UIView.animate(withDuration: 0.5, animations: { 
                self.pwview.didSelectedIndex(2)
                self.pwview.frame = CGRect(x: 0, y: 100, width: ScreenWidth, height: 42 * 6 + 60)
                self.pwview.layout.itemSize = CGSize(width: ScreenWidth, height: 42 * 6)
                self.pwview.m_view_calendar.frame = CGRect(x: 0, y: 60, width: ScreenWidth, height: 42 * 6)
                self.tableView?.frame = CGRect(x: 0, y: self.pwview.frame.maxY, width: ScreenWidth, height: ScreenHeight - 49 - self.pwview.frame.maxY)
            })
        }
        else if gesture.direction == .up {
            UIView.animate(withDuration: 0.5, animations: { 
                self.pwview.didSelectedIndex(1)
                self.pwview.frame = CGRect(x: 0, y: 100, width: ScreenWidth, height: 42 + 60)
                self.pwview.layout.itemSize = CGSize(width: ScreenWidth, height: 42)
                self.pwview.m_view_calendar.frame = CGRect(x: 0, y: 60, width: ScreenWidth, height: 42)
                self.tableView?.frame = CGRect(x: 0, y: self.pwview.frame.maxY, width: ScreenWidth, height: ScreenHeight - 49 - self.pwview.frame.maxY)
            })
        }
    }
}

// MARK: -  设置界面基本信息
extension KCWorkPlanController {
    internal func setupUI() {
        view.backgroundColor = colorBack
        setupBtn()
        setupCalendar()
        setupTableView()
    }
    
    // MARK: -  计划内和计划外按钮的点击事件
    @objc private func btnClick(sender: UIButton) {
//        let btnTag = sender.tag
        UIView.animate(withDuration: 0.2, animations: {
            self.bottonLineView.frame.origin.x = sender.frame.minX
        })
        self.getVisitorStoreData()
    }
    
    private func setupBtn() {
        view.addSubview(bgImageView)
        putInBtn = UIButton.creatBtn(fontSize: 16, title: "计划内")
        putOutBtn = UIButton(fontSize: 16, title: "计划外")
        let btnWidth = putInBtn.frame.size.width
        let btnHeight = 30
        putInBtn.frame = CGRect(x: ScreenWidth / 2 - btnWidth - 10, y: CGFloat(64), width: btnWidth, height: CGFloat(btnHeight))
        putInBtn.tag = 10
        putOutBtn.frame = CGRect(x: ScreenWidth / 2 + 10, y: CGFloat(64), width: btnWidth, height: CGFloat(btnHeight))
        putOutBtn.tag = 20
        putInBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        putOutBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        view.addSubview(putInBtn)
        view.addSubview(putOutBtn)
        
        //添加下面的线
        bottonLineView = UIView(frame: CGRect(x: putInBtn.frame.minX, y: 94, width: btnWidth, height: 3))
        bottonLineView.backgroundColor = UIColor.yellow
        view.addSubview(bottonLineView)
    }
    private func setupCalendar() {
        pwview.cellGetDataBlock = {
        }
        view.addSubview(pwview)
        pwview.selectDate = Date()
    }
    private func setupTableView() {
        tableView = UITableView(frame: CGRect(x: 0, y: pwview.frame.maxY, width: ScreenWidth, height: ScreenHeight - pwview.frame.maxY - 49), style: .plain)
        tableView?.backgroundColor = colorBack
        tableView?.tableFooterView = UIView()
        tableView?.delegate = self
        tableView?.dataSource = self
        tableView?.rowHeight = UITableViewAutomaticDimension
        tableView?.estimatedRowHeight = 60
        tableView?.register(UINib(nibName: "KCVisitorStoreCell", bundle: nil), forCellReuseIdentifier: "KCVisitorStoreCellId")
        view.addSubview(tableView!)
    }
}

// MARK: -  tableView的代理方法
extension KCWorkPlanController: UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.visitorStoreArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "KCVisitorStoreCellId", for: indexPath) as! KCVisitorStoreCell
        //设置cell
        setupCell(indexPath: indexPath, cell: cell)
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return headView1
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 45
    }
    private func setupCell(indexPath:IndexPath,cell:KCVisitorStoreCell) {
        cell.selectionStyle = .none
        cell.model = self.visitorStoreArray[indexPath.row]
        cell.delegate = self
    }
}

// MARK: -  拜访门店cell的按钮的点击事件------未提交按钮的点击事件----
extension KCWorkPlanController:VisitorStoreCellDelegate {
    // MARK: -  未完成按钮的点击事件----跳转到定位签到页面
    func btnDidClick(model: KCPlanModel?) {
        guard let model = model else { return }
        //判断是否是同一个时间
        let calender = Calendar.current
        let unitFlags = Set<Calendar.Component>([.day, .month, .year, .hour])     
        let compoments = calender.dateComponents(unitFlags, from: Date.init())
        let startDate = calender.date(from: compoments)
        sharedDateFormater.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let startTime = sharedDateFormater.date(from: model.PlanStartTime ?? "")
        let isSame = isSameDay(stardate: startDate!, startTime: startTime!)
        //过期的状态-----
        if model.TaskStatus == Expired {
            return
        }
        //未开始
        if model.TaskStatus == NotStart {
            if isSame == false {
                SVProgressHUD.showError(withStatus: "只能进行当天的拜访计划")
                return
            }
            if isVisiting() {
                SVProgressHUD.showError(withStatus: "请先完成其他的拜访计划")
                return
            }
            if model.TaskType == "940" {
                let visitorController = KCNoVisitorController()
                visitorController.planModel = model
                navigationController?.pushViewController(visitorController, animated: true)
            }else {
                //跳转到其他的页面----会议等
            }
        }
        //已经拜访-------
        if model.TaskStatus == HasEnded{
            if model.TaskType == "940" {
                //根据不同的类型来跳转
                let montnController = KCMontnReportController()
                montnController.model = model
                navigationController?.pushViewController(montnController, animated: true)
            }
            else {
                //跳转到其他的页面----会议等

            }
        }
        //拜访中
        if model.TaskStatus == Visiting {
            if isSame == false {
                SVProgressHUD.showError(withStatus: "只能进行当天的拜访计划")
                return
            }
            //根据不同的拜访类型进行跳转
            if model.TaskType == "940" {
                let montnController = KCMontnReportController()
                montnController.model = model
                navigationController?.pushViewController(montnController, animated: true)
            }
            else {
                //跳转到其他的页面----会议等

            }
        }
    }
    private func isSameDay(stardate:Date,startTime:Date) -> Bool {
        var isSame:Bool = false
        let calendar = Calendar.current
        let unitFlags = Set<Calendar.Component>([.day, .month, .year, .hour])
        var compoments1 = calendar.dateComponents(unitFlags, from: stardate)
        var compoments2 = calendar.dateComponents(unitFlags, from: startTime)
        if((compoments1.day! == compoments2.day!) && (compoments1.year! == compoments2.year!) && (compoments1.month! == compoments2.month!)) {
            isSame = true
        }
        return isSame
    }
    private func isVisiting() -> Bool {
        var isVisiting = false
        for planModel in allVisitorStoreArray {
            if planModel.TaskStatus == "5001010" {
                isVisiting = true
            }
        }
        return isVisiting
    }
}


// MARK: -  日历控件的代理方法
extension KCWorkPlanController :PWSCalendarDelegate {
    // MARK: -  点击某一个cell时候调用
    func pwsCalendar(_ _calendar: PWSCalendarView!, didSelecteDate _date: Date!) {
        // MARK: - 这句话感觉需要吗------
        //这句话----这句话需要吗?---------
        _calendar.selectDate = _date
        selDate = _date
        //获取往前日期的网络数据--------
        getVisitorStoreData()
        pwview.m_view_calendar.reloadData()
    }
    func chengeTheNumber(ofRows TheNumberOfRows: Int) {
        //根据改变的row的个数来改变frame
        changeCalendarFrame(rowNum: TheNumberOfRows)
    }
    
    func scroll(with date: Date!, block successBlock: PWSBlock!) {
        sharedDateFormater.dateFormat = "yyyy-MM-dd"
        KCNetworkManager.sharedTools.request(method: .GET, urlString: "/api/TaskPlan/InMonth", parameters:["Month":sharedDateFormater.string(from: date)]) { (response, error) in
            SVProgressHUD.dismiss()
            guard let response = response as? NSDictionary,            let responseContent = response["Content"] as? NSArray else {
                return
            }
            successBlock(responseContent as? [Any] ?? [])
        }
    }
    internal func changeCalendarFrame(rowNum: Int) -> Void {
        UIView.animate(withDuration: 0.3) {
            self.pwview.frame.size.height = CGFloat(42 * rowNum + 60)
            self.tableView?.frame = CGRect(x: 0, y: self.pwview.frame.maxY, width: ScreenWidth, height: ScreenHeight - 49 - self.pwview.frame.maxY)
        }
    }
}

// MARK: -  获取网络数据
extension KCWorkPlanController {
    //获取上面的排班的信息------
    internal func getFinishVsAllData() {
        SVProgressHUD.show()
        // MARK: -  获取销量提报完成总数----已经完成门店和总数
        KCNetworkManager.sharedTools.request(method: .GET, urlString: "/api/Task/GetSaleVolumeFinished", parameters: nil) {[weak self] (response, error) in
            SVProgressHUD.dismiss()
            guard let response = response as? NSDictionary,let responseContent = response["Content"] as? NSDictionary,let responseExtra = responseContent["Extra"] as? NSString,let responseFeedBackExtra = responseContent["FeedBackExtra"] as? NSString else {
                return
            }
            //处理获取的数据
            let extraArray = responseExtra.components(separatedBy: ";")
            self?.finishNum = extraArray.first ?? ""
            self?.allStoreNum = extraArray.last ?? ""
            let feedBackExtraArray = responseFeedBackExtra.components(separatedBy: "")
            self?.finishOutBack = feedBackExtraArray.first ?? ""
            self?.allOutBack = feedBackExtraArray.last ?? ""
        }
    }
    
    //获取下面的数据
    internal func getVisitorStoreData() {
        // MARK: -  启动的时候搜索当天的东西----------
        SVProgressHUD.show()
        var dic = [String:Any]()
        sharedDateFormater.dateFormat = "yyyy-MM-dd"
        let dateStr = sharedDateFormater.string(from: selDate)
        if self.bottonLineView.frame.origin.x == self.putInBtn.frame.minX {
            dic = ["TaskPlanType":"940010","DateTime":dateStr]
        }else if self.bottonLineView.frame.origin.x == self.putOutBtn.frame.minX {
            dic = ["TaskPlanType":"940020","DateTime":dateStr]
        }
        
        KCNetworkManager.sharedTools.request(method: .GET, urlString: "/api/TaskPlan/GetQueryVisitPlan", parameters: dic) {[weak self] (response, error) in
            guard let response = response as? NSDictionary,let responseContent = response["Content"] as? NSArray else {
                return
            }
            self?.visitorStoreArray = NSArray.yy_modelArray(with: KCPlanModel.self, json: responseContent) as? [KCPlanModel] ?? [KCPlanModel]()
            //获取
            self?.getAllVisitorStoreData()
            
            self?.tableView?.reloadData()
        }
    }
    //获取计划内和计划外的所有数据------用来判断是否可以继续拜访的
    internal func getAllVisitorStoreData() {
        // MARK: -  启动的时候搜索当天的东西----------
        SVProgressHUD.show()
        var dic = [String:Any]()
        sharedDateFormater.dateFormat = "yyyy-MM-dd"
        let dateStr = sharedDateFormater.string(from: selDate)
        dic = ["DateTime":dateStr]
        KCNetworkManager.sharedTools.request(method: .GET, urlString: "/api/TaskPlan/GetQueryVisitPlan", parameters: dic) {[weak self] (response, error) in
            SVProgressHUD.dismiss()
            guard let response = response as? NSDictionary,let responseContent = response["Content"] as? NSArray else {
                return
            }
            self?.allVisitorStoreArray = NSArray.yy_modelArray(with: KCPlanModel.self, json: responseContent) as? [KCPlanModel] ?? [KCPlanModel]()
        }
    }
    
}

